from django.shortcuts import redirect
from django.urls import reverse
from django.utils import timezone
from .models import TemporaryPassword


class TemporaryPasswordMiddleware:
    """临时密码中间件"""
    
    def __init__(self, get_response):
        self.get_response = get_response
    
    def __call__(self, request):
        # 检查用户是否已登录
        if request.user.is_authenticated:
            # 检查是否有有效的临时密码
            temp_password = TemporaryPassword.objects.filter(
                user=request.user,
                is_used=False,
                expires_at__gt=timezone.now()
            ).first()
            
            if temp_password:
                # 排除的URL路径，这些页面允许访问
                excluded_paths = [
                    '/accounts/force_change_password/',
                    '/accounts/logout/',
                    '/admin/',  # 允许管理员访问
                ]
                
                # 检查当前路径是否在排除列表中
                current_path = request.path
                is_excluded = any(current_path.startswith(path) for path in excluded_paths)
                
                # 如果不在排除列表中，重定向到密码修改页面
                if not is_excluded:
                    return redirect('accounts:force_change_password')
        
        response = self.get_response(request)
        return response